package com.hippo.core.ui.compose.control

import LoadingDialog
import android.util.Log
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImagePainter.State.Empty.painter
import coil.compose.rememberAsyncImagePainter
import com.hippo.core.R
import com.hippo.core.config.AppConsts
import com.hippo.core.core.ext.click
import com.hippo.core.core.ext.orZero
import com.hippo.core.core.ext.toJson
import com.hippo.core.core.manager.AppStore
import com.hippo.core.state.DeviceValue
import com.hippo.core.state.toWorkStatusIcon
import com.hippo.core.tuya.DpInfo
import com.hippo.core.tuya.DpType
import com.hippo.core.tuya.DpValue
import com.hippo.core.tuya.ThingControl
import com.hippo.core.tuya.toControlType
import com.hippo.core.tuya.toWifiResId
import com.hippo.core.ui.components.HorizontalSpacer
import com.hippo.core.ui.components.OptionButton
import com.hippo.core.ui.components.OutlineOptionButton
import com.hippo.core.ui.components.RemoteControl
import com.hippo.core.ui.components.TitleBar
import com.hippo.core.ui.components.VerticalSpacer
import com.hippo.core.ui.theme.ColorBackgroundPrimary
import com.hippo.core.ui.theme.HippoTheme

@Composable
fun ControlScreen(
    devId: String,
    onBack: () -> Unit,
    onSettingClick: (String?) -> Unit,
    onMonitorClick: (String) -> Unit,
    vm: ControlVM = viewModel(factory = ControlVMFactory(devId))
) {


    val uiState = vm.uiState

    if (uiState.isLoading) {
        LoadingDialog {

        }
    }

    LifecycleEventEffect(Lifecycle.Event.ON_CREATE) {
        vm.getDevice()
        vm.updateDeviceState()
        vm.getDeviceWifiSignal()
    }


    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = ColorBackgroundPrimary)
    ) {

        TitleBar(
            title = uiState.device?.name.orEmpty(),
            onBack = onBack,
            rightImageVector = Icons.Default.Settings,
            onRightClick = {
                onSettingClick(uiState.device?.name)
            }
        )

        Column(
            modifier = Modifier
                .background(color = ColorBackgroundPrimary)
                .padding(16.dp)
                .verticalScroll(rememberScrollState())
        ) {

            BatteryInfo(uiState.deviceValue, uiState.wifiSignal, uiState.device?.iconUrl)

            RemoteControl(
                centerChecked = uiState.deviceValue.switch_go == DpValue.SwitchGo.open || uiState.deviceValue.direction_control != DpValue.DirectionControl.stop,
                modifier = Modifier
                    .padding(top = 30.dp)
                    .align(Alignment.CenterHorizontally),
                onLeftClick = {
                    if (uiState.controlType == AppConsts.ControlType.MANUAL) {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.turn_left
                            ),
                            DpInfo(
                                DpType.MODE.dpId,
                                DpValue.Mode.random
                            ),
                        )
                    } else {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.turn_left
                            ),
                        )
                    }
                },
                onTopClick = {
                    if (uiState.controlType == AppConsts.ControlType.MANUAL) {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.forward
                            ),
                            DpInfo(
                                DpType.MODE.dpId,
                                DpValue.Mode.random
                            ),
                        )
                    } else {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.forward
                            ),
                        )
                    }
                },
                onRightClick = {
                    if (uiState.controlType == AppConsts.ControlType.MANUAL) {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.turn_right
                            ),
                            DpInfo(
                                DpType.MODE.dpId,
                                DpValue.Mode.random
                            ),
                        )
                    } else {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.turn_right
                            ),
                        )
                    }
                },
                onBottomClick = {
                    if (uiState.controlType == AppConsts.ControlType.MANUAL) {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.backward
                            ),
                            DpInfo(
                                DpType.MODE.dpId,
                                DpValue.Mode.random
                            ),
                        )
                    } else {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.backward
                            ),
                        )
                    }
                },
                onCenterClick = {
                    if (uiState.deviceValue.switch_go == DpValue.SwitchGo.open) {
                        vm.historyControlType = uiState.controlType
                        vm.publishDps(
                            DpInfo(
                                DpType.MODE.dpId,
                                DpValue.Mode.standby
                            ),
                            showLoading = true
                        )

                    } else {
                        val mode = when (vm.historyControlType) {
                            AppConsts.ControlType.MANUAL -> DpValue.Mode.random
                            AppConsts.ControlType.AUTO -> DpValue.Mode.smart
                            AppConsts.ControlType.EDGE -> DpValue.Mode.spiral
                            else -> null
                        }
                        if (mode != null) {
                            vm.publishDps(
                                DpInfo(
                                    DpType.MODE.dpId,
                                    mode
                                ),
                                showLoading = true
                            )
                        }
                    }
                },
                onStopClick = {
                    if (uiState.controlType == AppConsts.ControlType.MANUAL) {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.stop
                            )
                        )
                    } else {
                        vm.publishDps(
                            DpInfo(
                                DpType.DIRECTION_CONTROL.dpId,
                                DpValue.DirectionControl.stop
                            )
                        )
                    }

                }
            )

            val controlType = if(uiState.controlType == AppConsts.ControlType.STANDBY){
                vm.historyControlType
            } else{
                uiState.controlType
            }

            ControlButtonList(controlType) {

                if (it == AppConsts.ControlType.MONITOR) {
                    onMonitorClick(uiState.deviceValue.toJson())
                } else {
                    vm.historyControlType = it
                }

                Log.i("sss", "publishDps ControlScreen: ${vm.historyControlType}")

                when (it) {
                    AppConsts.ControlType.MANUAL -> {
                        if (uiState.speedy == 2) {
                            vm.publishDps(
                                DpInfo(
                                    DpType.MODE.dpId,
                                    DpValue.Mode.random
                                ),
                                DpInfo(
                                    DpType.SUCTION.dpId,
                                    DpValue.Suction.gentle
                                ),
                                showLoading = true
                            )
                        } else {
                            vm.publishDps(
                                DpInfo(
                                    DpType.MODE.dpId,
                                    DpValue.Mode.random
                                ),
                            )
                        }
                    }

                    AppConsts.ControlType.AUTO -> {
                        if (uiState.speedy == 2) {
                            vm.publishDps(
                                DpInfo(
                                    DpType.MODE.dpId,
                                    DpValue.Mode.smart
                                ),
                                DpInfo(
                                    DpType.SUCTION.dpId,
                                    DpValue.Suction.gentle
                                ),
                                showLoading = true
                            )
                        } else {
                            vm.publishDps(
                                DpInfo(
                                    DpType.MODE.dpId,
                                    DpValue.Mode.smart
                                ),
                                showLoading = true
                            )
                        }
                    }

                    AppConsts.ControlType.EDGE -> {
                        if (uiState.speedy == 2) {
                            vm.publishDps(
                                DpInfo(
                                    DpType.MODE.dpId,
                                    DpValue.Mode.spiral
                                ),
                                DpInfo(
                                    DpType.SUCTION.dpId,
                                    DpValue.Suction.gentle
                                ),
                                showLoading = true
                            )
                        } else {
                            vm.publishDps(
                                DpInfo(
                                    DpType.MODE.dpId,
                                    DpValue.Mode.spiral
                                ),
                                showLoading = true
                            )
                        }
                    }

                    AppConsts.ControlType.MONITOR -> {
                        onMonitorClick(uiState.deviceValue.toJson())
                    }
                }
            }

            VerticalSpacer(20.dp)


            when (controlType) {
                AppConsts.ControlType.MANUAL -> {
                    SpeedyControl(uiState.speedy) {
                        when (it) {
                            1 -> {
                                vm.publishDps(
                                    DpInfo(
                                        DpType.SUCTION.dpId,
                                        DpValue.Suction.gentle
                                    ),
                                    showLoading = true
                                )
                            }

                            2 -> {
                                vm.publishDps(
                                    DpInfo(
                                        DpType.SUCTION.dpId,
                                        DpValue.Suction.normal
                                    ),
                                    showLoading = true
                                )
                            }

                            3 -> {
                                vm.publishDps(
                                    DpInfo(
                                        DpType.SUCTION.dpId,
                                        DpValue.Suction.strong
                                    ),
                                    showLoading = true
                                )
                            }
                        }
                    }
                }

                AppConsts.ControlType.AUTO -> {
                    TwoButton(uiState.speedy) { speedy, suction ->
                        vm.publishDps(
                            DpInfo(
                                DpType.MODE.dpId,
                                DpValue.Mode.smart
                            ),
                            DpInfo(
                                DpType.SUCTION.dpId,
                                suction
                            ),
                            showLoading = true
                        )
                    }
                }

                AppConsts.ControlType.EDGE -> {
                    TwoButton(uiState.speedy) { speedy, suction ->
                        vm.publishDps(
                            DpInfo(
                                DpType.MODE.dpId,
                                DpValue.Mode.spiral
                            ),
                            DpInfo(
                                DpType.SUCTION.dpId,
                                suction
                            ),
                            showLoading = true
                        )
                    }
                }

            }
        }

    }


}


@Composable
fun BatteryInfo(deviceValue: DeviceValue, wifiSignal: Int, url: String?) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(color = Color.White, shape = MaterialTheme.shapes.medium)
            .padding(16.dp)
    ) {
        Column {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Image(
                    modifier = Modifier.size(30.dp, 18.dp),
                    painter = painterResource(id = R.mipmap.battery),
                    contentDescription = "Battery"
                )
                Text(
                    modifier = Modifier.padding(start = 10.dp),
                    text = "${deviceValue.battery_percentage.orZero()}%",
                    fontSize = 16.sp
                )
                Image(
                    modifier = Modifier
                        .padding(start = 10.dp)
                        .size(20.dp, 15.dp),
                    painter = painterResource(id = wifiSignal.toWifiResId()),
                    contentDescription = "Battery"
                )
            }

            Spacer(Modifier.height(10.dp))

            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {

                val statusIcon = deviceValue.toWorkStatusIcon()

                if (statusIcon != null) {
                    Image(
                        modifier = Modifier.size(18.dp),
                        painter = painterResource(id = statusIcon),
                        contentDescription = "Battery"
                    )
                }

                Text(
                    modifier = Modifier.padding(start = 5.dp),
                    text = ThingControl.parseWorkStatusName(deviceValue.status).orEmpty(),
                    fontSize = 18.sp
                )
            }

        }


        HorizontalSpacer(10.dp, Modifier.weight(1F))

        Image(
            painter = rememberAsyncImagePainter(
                model = url,
                placeholder = painterResource(id = R.mipmap.machine),
                error = painterResource(id = R.mipmap.machine)
            ),
            modifier = Modifier.size(200.dp, 50.dp),
            contentDescription = "Battery",
            alignment = Alignment.CenterEnd
        )
    }
}


@Composable
fun ControlButtonList(controlType: Int, onClick: (Int) -> Unit) {

    Row {
        OptionButton(
            text = stringResource(id = R.string.auto),
            checked = controlType == AppConsts.ControlType.AUTO,
            normalImage = painterResource(id = R.mipmap.auto_n),
            checkedImage = painterResource(id = R.mipmap.auto_s),
            onClick = {
                onClick(AppConsts.ControlType.AUTO)
            })

        HorizontalSpacer(10.dp, Modifier.weight(1F))


        OptionButton(
            text = stringResource(id = R.string.edge),
            checked = controlType == AppConsts.ControlType.EDGE,
            normalImage = painterResource(id = R.mipmap.edge_n),
            checkedImage = painterResource(id = R.mipmap.edge_s),
            onClick = {
                onClick(AppConsts.ControlType.EDGE)
            })


        HorizontalSpacer(10.dp, Modifier.weight(1F))

        OptionButton(
            text = stringResource(id = R.string.manual),
            checked = controlType == AppConsts.ControlType.MANUAL,
            normalImage = painterResource(id = R.mipmap.manual_n),
            checkedImage = painterResource(id = R.mipmap.manual_s),
            onClick = {
                onClick(AppConsts.ControlType.MANUAL)
            })
        HorizontalSpacer(10.dp, Modifier.weight(1F))

        OptionButton(
            text = stringResource(id = R.string.monitor),
            checked = controlType == AppConsts.ControlType.MONITOR,
            normalImage = painterResource(id = R.mipmap.monitor_n),
            checkedImage = painterResource(id = R.mipmap.monitor_s),
            onClick = {
                onClick(AppConsts.ControlType.MONITOR)
            })

    }
}


@Composable
fun SpeedyControl(speedyLevel: Int, onSpeedyChanged: (Int) -> Unit) {

    val speedyWeight by animateFloatAsState(
        when (speedyLevel) {
            0 -> 0F
            1 -> 1.5F
            2 -> 2F
            3 -> 3F
            else -> 0F
        }
    )

    val blankWeight by animateFloatAsState(
        when (speedyLevel) {
            0 -> 3F
            1 -> 2F
            2 -> 1.5F
            3 -> 0F
            else -> 3F
        }
    )

    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {

        Row {
            Image(
                modifier = Modifier.size(20.dp),
                painter = painterResource(id = R.mipmap.speedy0),
                contentDescription = "Battery"
            )
            Text(
                modifier = Modifier.padding(start = 10.dp),
                text = stringResource(R.string.speedy),
                fontSize = 16.sp
            )
        }

        VerticalSpacer(10.dp)

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    color = Color(0xFFEFEFEF), shape = RoundedCornerShape(35.dp)
                )
        ) {


            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(70.dp)
            ) {

                if (speedyWeight > 0) {
                    Text(
                        modifier = Modifier
                            .height(70.dp)
                            .weight(speedyWeight)
                            .background(
                                color = if (speedyLevel >= 1) MaterialTheme.colorScheme.primary else Color.White,
                                shape = RoundedCornerShape(56.dp)
                            ), text = ""
                    )
                }
                if (blankWeight > 0) {

                    Text(
                        modifier = Modifier
                            .height(70.dp)
                            .weight(blankWeight)
                            .background(
                                color = Color.Transparent, shape = RoundedCornerShape(56.dp)
                            ), text = ""
                    )
                }
            }




            Row(
                modifier = Modifier.fillMaxWidth()
            ) {

                Image(
                    modifier = Modifier
                        .size(70.dp)
                        .click {
                            if (speedyLevel > 0) {
                                onSpeedyChanged(speedyLevel - 1)
                            }
                        },
                    painter = painterResource(id = R.mipmap.minus),
                    contentDescription = "Battery"
                )
                Box(
                    modifier = Modifier
                        .weight(1F)
                        .height(70.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Image(
                        modifier = Modifier
                            .size(20.dp)
                            .click { onSpeedyChanged(1) },
                        painter = if (speedyLevel >= 1) painterResource(id = R.mipmap.speedy_w1)
                        else painterResource(
                            id = R.mipmap.speedy_b1
                        ),
                        contentDescription = "Battery"
                    )
                }

                Box(
                    modifier = Modifier
                        .weight(1F)
                        .height(70.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Image(
                        modifier = Modifier
                            .size(20.dp)
                            .click { onSpeedyChanged(2) },
                        painter = if (speedyLevel >= 2) painterResource(id = R.mipmap.speedy_w2)
                        else painterResource(
                            id = R.mipmap.speedy_b2
                        ),
                        contentDescription = "Battery"
                    )
                }

                Box(
                    modifier = Modifier
                        .weight(1F)
                        .height(70.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Image(
                        modifier = Modifier
                            .size(20.dp)
                            .click { onSpeedyChanged(3) },
                        painter = if (speedyLevel >= 3) painterResource(id = R.mipmap.speedy_w3)
                        else painterResource(id = R.mipmap.speedy_b3),
                        contentDescription = "speedy"
                    )
                }

                Image(
                    modifier = Modifier
                        .size(70.dp)
                        .click {
                            if (speedyLevel < 3) {
                                onSpeedyChanged(speedyLevel + 1)
                            }
                        },
                    painter = painterResource(id = R.mipmap.add),
                    contentDescription = "Battery"
                )

            }


        }

    }

}

@Composable
fun TwoButton(speedy: Int, onClick: (Int, String) -> Unit) {

    Row {

        OutlineOptionButton(
            modifier = Modifier
                .weight(1F),
            iconSize = 25.dp,
            text = stringResource(R.string.endurance),
            checked = speedy == 1 || speedy == 2,
            normalImage = painterResource(id = R.mipmap.time_n),
            checkedImage = painterResource(id = R.mipmap.time_s),
            onClick = {
                onClick(1, DpValue.Suction.gentle)
            }
        )

        HorizontalSpacer(20.dp)

        OutlineOptionButton(
            modifier = Modifier
                .weight(1F),
            iconSize = 25.dp,
            text = stringResource(R.string.high_performance),
            checked = speedy == 3,
            normalImage = painterResource(id = R.mipmap.efficient_n),
            checkedImage = painterResource(id = R.mipmap.efficient_s),
            onClick = {
                onClick(3, DpValue.Suction.strong)
            }
        )

    }

}


@Preview
@Composable
private fun ControlScreenPreview() {
    HippoTheme {
        ControlScreen(
            devId = "",
            onBack = {},
            onSettingClick = {},
            onMonitorClick = {}
        )
    }
}



